"""
朴素贝叶斯分类器实现
"""
import pandas as pd


def count_total(data):
    count = {}
    total = 0

    for index in data.index:
        specie = data.loc[index, 'species']
        count[specie] = data.loc[index, 'sweet'] + data.loc[index, 'not_sweet']
        total += count[specie]
    return count, total


def cal_base_rates(categories, total):
    cal_base_rates = {}
    for label in categories:
        priori_prob = categories[label]/total
        cal_base_rates[label] = priori_prob
    return cal_base_rates


def likelihold_prob(data, count):
    likelihold = {}
    for index in data.index:
        attr_prob = {}
        specie = data.loc[index, 'species']
        attr_prob['long'] = data.loc[index, 'long']/count[specie]
        attr_prob['not_long'] = data.loc[index, 'not_long']/count[specie]
        attr_prob['sweet'] = data.loc[index, 'sweet']/count[specie]
        attr_prob['not_sweet'] = data.loc[index, 'not_sweet']/count[specie]
        attr_prob['yellow'] = data.loc[index, 'yellow']/count[specie]
        attr_prob['not_yellow'] = data.loc[index, 'not_yellow']/count[specie]
        likelihold[specie] = attr_prob

    return likelihold


def navie_bayes_classifier(data, length=None, sweetness=None, color=None):
    count, total = count_total(data)
    # print("各个水果的总数：" + str(count))
    priori_prob = cal_base_rates(count, total)
    # print("各种水果的先验概率：" + str(priori_prob))
    likelihold = likelihold_prob(data, count)
    # print("各个特征在各种水果中的概率：" + str(likelihold))
    # ep = evidence_prob(data)
    # print("各个特征的先验概率：" + str(ep))
    res = {}
    for lable in data['species']:
        prob = priori_prob[lable]
        prob *= likelihold[lable][length] * likelihold[lable][sweetness] * likelihold[lable][color]
        res[lable] = prob
    print("预测结果：" + str(res))
    res = sorted(res.items(), key=lambda kv: kv[1], reverse=True)
    return res[0][0]


def main():
    # 定义数据集
    datasets_train = pd.read_csv('fruitclass_train.csv')
    datasets_test = pd.read_csv('fruitclass_test.csv')

    for index in datasets_test.index:
        long = datasets_test.loc[index, 'long']
        sweet = datasets_test.loc[index, 'sweet']
        color = datasets_test.loc[index, 'yellow']
        print("特征值：[{0}, {1}, {2}]".format(long, sweet, color))
        res = navie_bayes_classifier(datasets_train, long, sweet, color)
        print("水果类别：" + res)


if __name__ == '__main__':
    main()